﻿using BLL;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using webui.Models;
using Tools;
using webui.ViewModel;

namespace webui.Areas.Admin.Controllers
{
    public class NewsController : Controller
    { 

        public NewsContentBLL inews = new NewsContentBLL();

        public  NewsTypeBLL inewtype = new NewsTypeBLL();

        public NewsCommentBLL inewcomment = new NewsCommentBLL();

        // GET: Admin/News
        [HttpGet]
        /// <summary>
        /// 视图页面
        /// </summary>
        /// <returns></returns>
        [SkipPemission]
        public ActionResult NewsView()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem() { Text = "所有类型", Value = "0", Selected = true });
            list.AddRange(inewtype.GetList(p => p.isDel == false).Select(p => new SelectListItem() { Text = p.typeName, Value = p.id.ToString() }).ToList());
            ViewBag.newstype = list;
            return View();
        }

        [HttpPost]
        /// <summary>
        /// 新闻列表 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult NewList()
        {
            //获取页容量
            int pageSize = 10;
            //获取请求的页码
            int pageIndex = 1;
         
            string sqlRows = "SELECT count(1 ) FROM dbo.NewsContent n INNER JOIN dbo.NewsType t ON n.newsTypeid=t.id where 1=1";
            if (!string.IsNullOrEmpty(Request.Form["rows"]))
            {
                int.TryParse(Request.Form["rows"], out pageSize);
            }
            if (!string.IsNullOrEmpty(Request.Form["page"]))
            {
                int.TryParse(Request.Form["page"], out pageIndex);
            } 
            string sql = "SELECT n.id,n.title,n.newsImage,t.typeName,n.addtime FROM dbo.NewsContent n INNER JOIN dbo.NewsType t ON n.newsTypeid=t.id where 1=1";
            if (Request.Form["typeid"] != null && Request.Form["typeid"].Trim() != "0")
            {
                sql += " and n.newsTypeid=" + Request.Form["typeid"];
                sqlRows += " and n.newsTypeid=" + Request.Form["typeid"];
            } 
            if (Request.Form["keyword"] != null && Request.Form["keyword"].Trim() != "")
            { 
                sql += $" and content LIKE '%{Request.Form["keyword"].Trim()}%' "  ;
                sqlRows += $" and content LIKE '%{Request.Form["keyword"].Trim()}%' ";
            }
            
            sql +=  $"ORDER BY n.id DESC    OFFSET({pageIndex-1}) * {pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY  ;";

            DataTable dt= inews.GetTableBySQL(sql,null);
             object rowCount=   inews.GetScalarBySQL(sqlRows, null);
            int totle = 0;
            if ( rowCount !=null )
            {
                totle= Convert.ToInt32(rowCount);
            }
  
            //2 生成规定格式的 json字符串发回 给 异步对象
            DataGridModel dgModel = new DataGridModel()
            {
                total = totle,
                rows = dt.ToList<V_NewsList>(),
                footer = null
            };
            return Json(dgModel);
        }




        /// <summary>
        /// 显示 新增新闻列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxRequest]
        [SkipPemission]
        public ActionResult AddNews()
        { 
            SetDropDonwList(1);
            return PartialView("AddNews");
        }

        //异步上传图片
        [SkipPemission]
        public ActionResult FileUpload()
        {
            //保存上传的图片
            HttpPostedFileBase imgFile = Request.Files[0];

            string imgname = Guid.NewGuid().ToString();
            if (imgFile.ContentType.Contains("image/")) //图片类型
            {
                string ename = Path.GetExtension(imgFile.FileName);//获取扩展名
                imgname = imgname + ename;
                imgFile.SaveAs(Server.MapPath("../upImg/" + imgname));
                return Content("ok|" + imgname);
            }
            else
            {
                return Content("err|图片格式不对或为选择图片");
            }


        }

        /// <summary>
        /// 新增新闻
        /// </summary>
        /// <param name="newsModl"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveNews(NewsContent newsModl)
        {
            if (!((string.IsNullOrEmpty(newsModl.title) || string.IsNullOrEmpty(newsModl.content) || newsModl.newsTypeid == 0)))
            {
                newsModl.addtime = DateTime.Now;
                newsModl.isDel = false;
                newsModl.username = OperateContext.Current.Usr.id;
                newsModl.states = true;
                newsModl.content = Server.HtmlEncode(newsModl.content); //将HTML编码。
                newsModl.hot = 0;
                try
                {
                    inews.Insert(newsModl);
                    return OperateContext.Current.RedirectAjax("ok", "添加成功", null, "newsview");
                }
                catch (Exception ce)
                {
                    return OperateContext.Current.RedirectAjax("err", "添加失败" + ce.Message, null, "");
                }

            }
            else
            {
                return OperateContext.Current.RedirectAjax("err", "信息未填写完整", null, "");
            }

        }

        /// <summary>
        /// 修改新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, AjaxRequest]
        public ActionResult Editnews(int id)
        {
            //根据id查询要修改的权限
            var model = inews.GetList(p => p.id == id).FirstOrDefault();
            model.content = Server.HtmlDecode(model.content);
            SetDropDonwList();

            //将 新闻对象 传给 视图 的 Model属性
            return PartialView(model);
        }

        /// <summary>
        /// 新闻详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SkipPemission]
        public ActionResult detailNews(int id)
        {
            //根据id查询要修改的权限
            var premodle = inews.GetList(p => p.id == id).FirstOrDefault();
            ViewBag.newstype = premodle.newsTypeid;
            ViewBag.person = "暂无"; 


            premodle.content = Server.HtmlDecode(premodle.content);

            //将 新闻对象 传给 视图 的 Model属性
            return PartialView(premodle);
        }



        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Editnews(NewsContent newsmodl)
        {

            if (!((string.IsNullOrEmpty(newsmodl.title) || string.IsNullOrEmpty(newsmodl.content) || newsmodl.newsTypeid == 0 || newsmodl.id == 0)))
            {
                newsmodl.username = OperateContext.Current.Usr.id;
                newsmodl.content = Server.HtmlEncode(newsmodl.content); //将HTML编码。
                try
                {
                    inews.Update(u => new NewsContent {
                        title = newsmodl.title,
                        content = newsmodl.content,
                        username=newsmodl.username,
                        newsImage = newsmodl.newsImage,
                        newsTypeid = newsmodl.newsTypeid,
                        newsSource = newsmodl.newsSource
                    } , u=> u.id==newsmodl.id);
                     

                    return OperateContext.Current.RedirectAjax("ok", "修改成功", null, "newsview");
                }
                catch (Exception ce)
                {
                    return OperateContext.Current.RedirectAjax("err", "修改失败" + ce.Message, null, "");
                }

            }
            else
            {
                return OperateContext.Current.RedirectAjax("err", "信息未填写完整", null, "");
            }



        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DleNews(int id)
        {
            try
            {
                // 先删除评论
                inewcomment.Delete(a => a.newsid == id);

                inews.Delete(p => p.id == id);
                return OperateContext.Current.RedirectAjax("ok", "删除成功", null, "");
            }
            catch (Exception)
            {

                return OperateContext.Current.RedirectAjax("err", "操作失败", null, ""); ;
            }


        }



        /// <summary>
        /// 设置要显示的下拉列表
        /// </summary>
        /// <param name="typeid"></param>
        private void SetDropDonwList(int typeid = 1)
        {
            var list = inewtype.GetList(p => p.isDel == false).Select(p => new SelectListItem() { Text = p.typeName, Value = p.id.ToString() }).ToList();
            if (typeid != 1)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Value == typeid.ToString())
                    {
                        list[i].Selected = true;
                        break;
                    }
                }
            }
            else
            {
                list[1].Selected = true;
            }



            ViewBag.newstype = list;
        }

    }
}